package com.x.reader.service;

import com.x.framework.Base;
import com.x.framework.exception.BusinessException;
import com.x.framework.exception.ExceptionCode;
import com.x.framework.service.BaseService;
import com.x.reader.dao.*;
import com.x.reader.model.*;
import org.directwebremoting.io.FileTransfer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class PaperService extends BaseService {

    @Autowired
    private PaperDao paperDao;

    public List<Paper> selectPaperList(Paper paper) {
        try {
            return paperDao.selectPaperList(paper);
        } catch (Exception e) {
            throw new BusinessException(ExceptionCode.EXCEPTION_CODE0000, e);
        }
    }

    public Paper insertPaper(Paper paper, FileTransfer paperCoverFile) {
        try {
            String paperId = this.getUid(32);
            String paperCover = paperCoverFile.getFilename();
            paperCover = paperId + paperCover.substring(paperCover.lastIndexOf(".")).toLowerCase();
            paper.setPaperId(paperId);
            paper.setPaperCover(paperCover);
            paper.setPaperCreateTime(Base.getCurrentDate(0, "yyyy-MM-dd HH:mm:ss"));
            paper = this.insert(paper);
            this.uploadFile(paperCoverFile, "/upload/paper/cover", paperCover);
            return paper;
        } catch (Exception e) {
            throw new BusinessException(ExceptionCode.EXCEPTION_CODE0000, e);
        }
    }

    public void updatePaper(Paper paper, FileTransfer paperCoverFile) {
        try {
            String paperId = paper.getPaperId();
            String paperCover = null;
            if (Base.isNotNull(paperCoverFile)) {
                paperCover = paperCoverFile.getFilename();
                paperCover = paperId + paperCover.substring(paperCover.lastIndexOf(".")).toLowerCase();
                paper.setPaperCover(paperCover);
            }
            paper.setPaperCreateTime(Base.getCurrentDate(0, "yyyy-MM-dd HH:mm:ss"));
            this.update(paper);

            if (Base.isNotNull(paperCover)) {
                this.deleteFile("/upload/paper/cover", paperCover);
                this.uploadFile(paperCoverFile, "/upload/paper/cover", paperCover);
            }
        } catch (Exception e) {
            throw new BusinessException(ExceptionCode.EXCEPTION_CODE0000, e);
        }
    }

    public void deletePaper(Paper paper) {
        try {
            if (Base.isNotNull(paper.getPaperCover())) {
                this.deleteFile("/upload/paper/cover", paper.getPaperCover());
            }
            Paper p = new Paper();
            p.setPaperId(paper.getPaperId());
            this.delete(p);
        } catch (Exception e) {
            throw new BusinessException(ExceptionCode.EXCEPTION_CODE0000, e);
        }
    }

}
